//itob(n,s,b) that converts the integer n into a base b character representation in the string s

//In particular, itob(n,s,16) formats s as a hexadecimal integer in s. 

#include <stdio.h>

void itob(int n, char s[], int b);
int clear(char* c, int count);
void reverse(char s[]);
#define MAGIC_1 2048
#define MIN_INT -2147483648


int main()
{
  char s[MAGIC_1];
    


  int k= MIN_INT;
  //  int l = -k;
  //printf("l: %i\n",l);
  //	 itoa(  -2147483648,s);
  // 	 printf("%s\n",s);
  for(;;)
    {
      clear(s,MAGIC_1);
	 itob(k,s,2);
	 printf("b: %i, %i :\t %s\n",2,k,s);
	 
      clear(s,MAGIC_1);
	 itob(k,s,8);
 	 printf("b: %i, %i :\t %s\n",8,k,s);

	 
      clear(s,MAGIC_1);
	 itob(k,s,10);
  	 printf("b: %i, %i :\t %s\n",10,k,s);

      clear(s,MAGIC_1);
	 itob(k,s,16);
   	 printf("b: %i, %i :\t %s\n",16,k,s);

      clear(s,MAGIC_1);
	 itob(k,s,64);
   	 printf("b: %i, %i :\t %s\n",64,k,s);

	 
	 k*=2;
    }
    
  return 0;
}  

void itob(int n, char s[], int b)
{
  int i, sign, specialcase=0;

       if ((sign = n) < 0)  /* record sign */
	    {
		 if (n != MIN_INT)
		   n = -n;          /* make n positive */
		 else  //special case
		   {
			n++;
			n = -n;
			specialcase=1;
		   } 
	    }
	  
       i = 0;

	  
       do {      /* generate digits in reverse order */
	    if ((i == 0) && specialcase ) 
		 {
		   s[i] = n % b + '1';
		   if (s[i] > '9') s[i]+=7;
		   i++;
		 }/* get next digit */
	    else
		 {
		   s[i] = n % b + '0';  /* get next digit */
		   if (s[i] > '9') s[i]+=7;	   
		   i++;
		 }
       }  
	  while ((n /= b) > 0);    /* delete it */
	  //	  if (specialcase && b==2) //binary is kind of special.
	  //  {
	  //	 s[i]='1';
	  //	 i++;
	  // }

  	  if (specialcase)
	    {
		 for(int k =0 ;k<=i+1;k++)
		   if (((b <= 9) && (s[k] >= b+'0')) || ((b > 9) && (s[k] >= b+'0'+7)))
		   {
			s[k]='0';
			if (((s[k+1]==0) && (b==2)) || (s[k+1]=='0')) s[k+1]='1';
			else s[k+1]++;
		   }
		   
	    }	  
	  if (specialcase && b==2) i++; //this is the only one that necessitates one more position i think?
	  
       if (sign < 0)
           s[i++] = '-';
       s[i] = '\0';
	  reverse(s);
}


void reverse(char s[])
{
  if (s!=0)
    {
	 int i=0;
	 while (s[i]!=0)
         i++;
	 char temp[i];
	 for (int j=0; j<i; j++)
	   {
		temp[j]=s[i-(j+1)];
	   }

	 for (int j=0; j<i; j++)
	   {
		s[j]=temp[j];
		s[j+1]=0;
	   }
	 
    }
}



int clear(char* c, int count)
{
  for (int i=0; i<count;i++)
    {c[i]=0;}
  return 0;
}
